<template>
  <el-form
    label-width="100px"
    :model="skuInfo"
    :rules="skuRules"
    ref="skuFormRef"
  >
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        class="mx-4"
        style="width: 100%"
        :min="1"
        :max="1000"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="100"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" type="textarea" rows="4" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(attr, index) in attrList"
          :key="attr.id"
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
        >
          <el-form-item :label="attr.attrName">
            <el-select
              v-model="skuInfo.skuAttrValueList[index]"
              @change="clearAttrRules"
            >
              <el-option
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                :label="attrValue.valueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(saleAttr, index) in spuSaleAttrList"
          :key="saleAttr.id"
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
        >
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select
              v-model="skuInfo.skuSaleAttrValueList[index]"
              @change="clearSaleAttrRules"
            >
              <el-option
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                :label="saleAttrValue.saleAttrValueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        :data="spuImageList"
        @selection-change="handleSelectionChange"
        border
      >
        <!-- 这一行是复选框的 -->
        <el-table-column type="selection" width="60"></el-table-column>
        <!-- 这个是图片的 -->
        <el-table-column label="图片" prop="skuImageList">
          <template v-slot="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :alt="row.imgName"
              :src="row.imgUrl"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="图片名称"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              v-if="row.isDefault === '0'"
              @click="setDefaultImage(row)"
              >设置为默认项</el-button
            >
            <el-button type="success" v-else disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm(skuFormRef)">保存</el-button>
      <el-button @click="emits('changeScene', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm',
}
</script>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqGetAttrListData } from '@/api/product/attr'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { useCategoryListStore } from '@/stores/categoryList'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryListStore()
const props = defineProps(['currentSpuInfo', 'aaa'])
const emits = defineEmits(['changeScene'])

const skuFormRef = ref<FormInstance>()
interface User {
  date: string
  name: string
  address: string
}

// 定义三个变量来存储相应会来的数据
const spuImageList = ref([])
const spuSaleAttrList = ref([])
const attrList = ref([])
// 准备添加SkuInfo时的参数数据
const skuInfo = reactive({
  // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
})

// 书写一个图片的自定义校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  console.log('rule', rule, value, callback)
  if (value.length === 0) {
    callback('请至少选择一张图片...')
    return
  }
  if (!value.find((item) => item.isDefault === '1')) {
    callback('请选择默认图6片...')
    return
  }
  callback() // 什么参数都不写，表示放行
}

// 定义校验规则
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入sku名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在1到10之间', trigger: 'blur' },
  ],
  price: [{ required: true, message: '请输入sku价格', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入sku重量', trigger: 'blur' }],
  skuDesc: [{ required: true, message: '请输入sku描述', trigger: 'blur' }],
  skuAttrValueList: [
    // 平台属性校验规则
    {
      required: true,
      message: '请至少选择一个平台属性',
      type: 'array',
      trigger: 'change',
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: '请至少选择一个销售属性',
      type: 'array',
      trigger: 'change',
    },
  ],
  skuImageList: [
    { required: true, validator: skuImageListValidate, trigger: 'change' },
  ],
})

// 1. 获取页面中一开始就要渲染的数据
onMounted(async () => {
  // all可以一次性发送多个请求，如果成功，则会将返回值按书写顺序赋值,有一个失败，则最终结果 都是reject 都失败了 整体性比较强
  // allSettled 可以一次性发送多个请求 即使有个别的失败也不会影响整体结果
  // 可以有成功，也可以有失败 响应结果还是按顺序赋值
  const spuId = props.currentSpuInfo.id
  const [resSpuImageList, resSpuSaleAttrList, resAttrList] =
    await Promise.allSettled([
      reqGetSpuImageList(spuId),
      reqGetSpuSaleAttrList(spuId),
      reqGetAttrListData({
        category1Id: categoryStore.category1Id as number,
        category2Id: categoryStore.category2Id as number,
        category3Id: categoryStore.category3Id as number,
      }),
    ])
  // console.log('skuForm', resSpuImageList, resSpuSaleAttrList, resAttrList)
  // 先进行判断，然后在赋值,当成功了之后状态码就会变成fulfilled
  if (resSpuImageList?.status === 'fulfilled') {
    // spuImageList.value = resSpuImageList.value
    spuImageList.value = resSpuImageList.value.map((item) => {
      return {
        ...item,
        isDefault: '0', // 0 表示正常显示 1 表示默认项
      }
    })
  }
  if (resSpuSaleAttrList?.status === 'fulfilled') {
    spuSaleAttrList.value = resSpuSaleAttrList.value
  }
  if (resAttrList?.status === 'fulfilled') {
    attrList.value = resAttrList.value
  }
})

// 2. 设置图片默认选项
const setDefaultImage = (row) => {
  // console.log('aaa', row, spuImageList)

  // 2.1 需要进行排它  先将之前的设置为正常
  spuImageList.value.forEach((item) => {
    item.isDefault = '0'
  })
  // 2.2 再将当前被单击的设置为默认项
  row.isDefault = '1'
  // 2.3 将当前默认项收集起来
  skuInfo.skuDefaultImg = row.imgUrl
}

// 3. 收集图片数据
const handleSelectionChange = (val) => {
  // val就是我们选择的数据,就是选着了几张图就有几条数据
  // console.log('skuImg', val)
  skuInfo.skuImageList = val
}
// 4. 添加skuInfo  内部有校验
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!')
      // if(!skuInfo.skuDefaultImg){
      //   ElMessage.error('请选择默认图片...')
      //   return
      // }
      skuInfo.spuId = props.currentSpuInfo.id
      skuInfo.category3Id = props.currentSpuInfo.category3Id
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [attrId, attrName, valueId, valueName] = item.split(':')
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          }
        })
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
            item.split(':')
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          }
        })
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success('添加sku数据成功...')
      emits('changeScene', 1)
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 5. 清空平台属性的校验规则
const clearAttrRules = () => {
  skuFormRef.value?.clearValidate(['skuAttrValueList'])
}
// 6. 清空销售属性的校验规则
const clearSaleAttrRules = () => {
  console.log('事件触发...aaaa')
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}
</script>
<style></style>
